<template>
  <div class="front">
    <el-form :model="searchForm" label-width="120px">
      <el-form-item class="input" label="店铺名称">
        <el-input v-model="searchForm.name" />
      </el-form-item>
      
    </el-form>
    <el-button class="search" type="primary">查询</el-button>
  </div>


  <div class="tail">
    <div class="tail-action">
     
      <!-- <el-button type="primary"  @click="openAdd">新增</el-button> 使用随机编码-->
      <el-button type="primary" @click="dialogVisible1 = true"  >新增</el-button>
      <el-button  type="primary"  @click="handleChangeStatus">启用</el-button>
      <el-button  type="primary"  @click="handleChangeStatus1">停用</el-button> 
    </div>
    <el-table :data="tableData()" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
    
      <el-table-column prop="shopCode" label="店铺编号" width="90PX" />
      <el-table-column prop="shopFullName" label="平台店铺全称" min-width="60PX" />
      <el-table-column prop="shopPlatform" label="店铺所属平台" min-width="60PX" />
      <el-table-column prop="shopSimpleName" label="内部店铺简称" min-width="60PX" />
      <el-table-column prop="companyName" label="所属公司全称" min-width="50PX" />
      <el-table-column prop="marketer" label="营销人" min-width="50PX" />
      <el-table-column prop="status" label="商户状态" width="100" :filter-multiple="false" :filters="[
  { text: '停用', value: 1 },
  { text: '启用', value: 0 },
]" :filter-method="filterTag" filter-placement="bottom-end">
  <template #default="scope">
    <el-tag :type="scope.row.status == 0? 'success' : 'danger'" disable-transitions>{{ scope.row.status == 1? '停用' : '启用' }}</el-tag>
  </template>
</el-table-column>
    
      <el-table-column prop="createTime" label="添加时间" min-width="80PX" />
      <el-table-column fixed="right" label="操作" min-width="60">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleOpenEdit(scope.row)">编辑</el-button>
          <el-button link type="primary" size="small" @click="handleOpenEdit(scope.row)">设置扣点</el-button>
          <el-button link type="primary" size="small" @click="handleDeleteStreamShop(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
        layout="prev, pager, next ,total,sizes" :total="data.total" @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </div>
  </div>

  <div class="dialog-list">
    <el-dialog v-model="dialogVisible1" title="新建角色" width="30%" :close-on-click-modal="true" :show-close="false">
  <div>
    <el-form :model="streamShopForm" label-width="120px" :rules="streamShopRules"  ref="streamShopRef">
      <!-- 店铺编码预生成（假设这里是一个只读的输入框展示预生成编码） -->
      <el-form-item label="店铺编码预生成" prop="shopCode" :required="true">
        <el-input v-model="streamShopForm.shopCode" ></el-input>
      </el-form-item>
      <!-- 店铺所在平台（下拉选择） -->
      <el-form-item label="店铺所在平台" prop="shopPlatform" :required="true">
        <el-select v-model="streamShopForm.shopPlatform" placeholder="请选择平台">
          <el-option label="抖音" value="抖音"></el-option>
          <el-option label="快手" value="快手"></el-option>
          <el-option label="拼多多" value="拼多多"></el-option>
          <el-option label="微信视频号" value="微信视频号"></el-option>
          <el-option label="淘宝天猫" value="淘宝天猫"></el-option>
          <el-option label="今日头条" value="今日头条"></el-option>
          <el-option label="小红书" value="小红书"></el-option>
          <el-option label="百度" value="百度"></el-option>
          <el-option label="哔哩哔哩" value="哔哩哔哩"></el-option>
          <el-option label="微信小程序" value="微信小程序"></el-option>
          <el-option label="支付宝" value="支付宝"></el-option>
          <el-option label="对庄app" value="对庄app"></el-option>
          <el-option label="阿里拍卖" value="阿里拍卖"></el-option>
          <el-option label="微拍堂" value="微拍堂"></el-option>
          <el-option label="玩物得志" value="玩物得志"></el-option>
          <el-option label="有赞" value="有赞"></el-option>
          <el-option label="私域" value="私域"></el-option>
          <el-option label="Tik Tok" value="Tik Tok"></el-option>
          <el-option label="Facebook" value="Facebook"></el-option>
          <el-option label="其他" value="其他"></el-option>
        </el-select>
      </el-form-item>
      <!-- 平台店铺全称 -->
      <el-form-item label="平台店铺全称" prop="shopFullName" :required="true">
        <el-input v-model="streamShopForm.shopFullName" />
      </el-form-item>
      <!-- 内部店铺简称 -->
      <el-form-item label="内部店铺简称" prop="shopSimpleName" :required="true">
        <el-input v-model="streamShopForm.shopSimpleName" />
      </el-form-item>
      <!-- 所属公司全称 -->
      <el-form-item label="所属公司全称" prop="companyName" :required="true">
        <el-input v-model="streamShopForm.companyName" />
      </el-form-item>
      
      <!-- 营销人 -->
      <el-form-item label="营销人" prop="marketer" :required="true">
        <el-input v-model="streamShopForm.marketer" />
      </el-form-item>
      
    </el-form>
  </div>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible1 = false">取消</el-button>
      <el-button type="primary" @click="handleAddStreamShop">
        确认
      </el-button>
    </span>
  </template>
</el-dialog>


    <el-dialog v-model="dialogVisible2" title="编辑用户" width="30%" :before-close="handleClose" :show-close="false">
      <div>
        <el-form :model="streamShopForm" label-width="120px" :rules="streamShopRules"  ref="streamShopRef">
      <!-- 店铺编码预生成（假设这里是一个只读的输入框展示预生成编码） -->
      <el-form-item label="店铺编码预生成" prop="shopCode" :required="true">
        <el-input v-model="streamShopForm.shopCode" ></el-input>
      </el-form-item>
      <!-- 店铺所在平台（下拉选择） -->
      <el-form-item label="店铺所在平台" prop="shopPlatform" :required="true">
        <el-select v-model="streamShopForm.shopPlatform" placeholder="请选择平台">
          <el-option label="抖音" value="抖音"></el-option>
          <el-option label="快手" value="快手"></el-option>
          <el-option label="拼多多" value="拼多多"></el-option>
          <el-option label="微信视频号" value="微信视频号"></el-option>
          <el-option label="淘宝天猫" value="淘宝天猫"></el-option>
          <el-option label="今日头条" value="今日头条"></el-option>
          <el-option label="小红书" value="小红书"></el-option>
          <el-option label="百度" value="百度"></el-option>
          <el-option label="哔哩哔哩" value="哔哩哔哩"></el-option>
          <el-option label="微信小程序" value="微信小程序"></el-option>
          <el-option label="支付宝" value="支付宝"></el-option>
          <el-option label="对庄app" value="对庄app"></el-option>
          <el-option label="阿里拍卖" value="阿里拍卖"></el-option>
          <el-option label="微拍堂" value="微拍堂"></el-option>
          <el-option label="玩物得志" value="玩物得志"></el-option>
          <el-option label="有赞" value="有赞"></el-option>
          <el-option label="私域" value="私域"></el-option>
          <el-option label="Tik Tok" value="Tik Tok"></el-option>
          <el-option label="Facebook" value="Facebook"></el-option>
          <el-option label="其他" value="其他"></el-option>
        </el-select>
      </el-form-item>
      <!-- 平台店铺全称 -->
      <el-form-item label="平台店铺全称" prop="shopFullName" :required="true">
        <el-input v-model="streamShopForm.shopFullName" />
      </el-form-item>
      <!-- 内部店铺简称 -->
      <el-form-item label="内部店铺简称" prop="shopSimpleName" :required="true">
        <el-input v-model="streamShopForm.shopSimpleName" />
      </el-form-item>
      <!-- 所属公司全称 -->
      <el-form-item label="所属公司全称" prop="companyName" :required="true">
        <el-input v-model="streamShopForm.companyName" />
      </el-form-item>
      
      <!-- 营销人 -->
      <el-form-item label="营销人" prop="marketer" :required="true">
        <el-input v-model="streamShopForm.marketer" />
      </el-form-item>
      
    </el-form>
      </div>
      <template #footer>
     <span class="dialog-footer">
       <el-button @click="dialogVisible2 = false">取消</el-button>
       <el-button type="primary" @click="handleUpdateStreamShop">确认</el-button>
     </span>
   </template>
    </el-dialog>

  </div>
</template>
     
<script >
import { ref, defineComponent, reactive, toRefs, } from "vue";
import { ElMessageBox, ElMessage } from 'element-plus'
import { onMounted } from "vue";
import { addStreamShop,deleteStreamShop,editStreamShop, getStreamShopList ,startOrStopStreamShop} from "@/api/schedule/schedule"

export default defineComponent({
  name: "StreamShop",
  components: {},

  setup() {
    let selectedRows = ref([]); // 使用ref来响应式地初始化selectedRows
    let streamShopData = reactive({
      data: [],
    });
 
    const streamShopRef = ref(null)
    const streamShopForm = reactive({
    id:'',
    shopCode:'',
    shopFullName:'',
      streamShopName: '',
      shopSimpleName:'',
      companyName:'',
      marketer:'',
     
      
      createTime:'',
      // streamShopKey: '',
      // streamShopSort: '1',
      // menuIds: [],
      // shopPlatform:'',
      
      // password: '',
      // platform:'',
     status: 0,
     options: [
        {value: 0,label: '启用'},
        {value: 1,label: '禁用'},
      ]
    });
    const searchForm = reactive({
      name: '',
      status: 0,  //yyl添加
    });
    let dialogVisible1 = ref(false)
    const dialogVisible2 = ref(false)
    const streamShopRules = reactive({
      streamShopName: [{ required: true, message: '请输入内容', trigger: 'blur' },
      { min: 3, max: 10, message: '账号长度 在 3 到 10长度之间', trigger: 'blur' }],
    });


    //表格用到的参数
    let state = reactive({
      data: {
        page: 1,
        limit: 10,
        total: streamShopData.data.length,
      }
    });

    const filterTag = (value, row) => {
      return row.status == value
    }
    onMounted(() => {
      handleGetStreamShopList(state.data.page, state.data.limit)
    })


    const handleGetStreamShopList = (page, limit) => {
      getStreamShopList(page, limit).then((res) => {
        streamShopData.data = res.rows
        state.data.total = res.total
      })
    }
    const tableData = () => {
      return streamShopData.data
    };
    //改变页码
    const handleCurrentChange = (e) => {
      state.page = e;
      handleGetStreamShopList(e, state.data.limit)
    };
    //改变页数限制
    const handleSizeChange = (e) => {
      state.limit = e;
      handleGetStreamShopList(state.data.page, e)
    };
    // //生成随机编码
    // const openAdd = () => {
    //   dialogVisible1.value = true
    //   getSupplierCode().then((res) => {
    //     supplierForm.supplierCode = res
    //   })
    // }


//添加角色
const handleAddStreamShop = () => {
  if (streamShopRef.value === null) {
       console.error('streamShopRef is null');
       return;
     }
      streamShopRef.value.validate().then(() => {//验证通过
        addStreamShop(streamShopForm).then((res) => {
          res.code == 200 ? ElMessage.success('添加成功') : ElMessage.error(res.msg)
          clearForm()
          dialogVisible1.value = false
          handleGetStreamShopList(state.data.page, state.data.limit)
        })
      }).catch(()=>{
        
      })
};

//删除角色
//删除角色
const handleDeleteStreamShop = (id) => { 
  ElMessageBox.confirm(
    '是否要删除该用户?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      deleteStreamShop(id).then(() => {
        handleGetStreamShopList(state.data.page, state.data.limit)
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
};


const handleOpenEdit = (data) => {
  dialogVisible2.value = true;
  streamShopForm.id = data.id;
  streamShopForm.shopCode = data.shopCode;
  streamShopForm.shopPlatform = data.shopPlatform; // 确保这个字段名在数据中是正确的
  streamShopForm.shopFullName = data.shopFullName;
  streamShopForm.shopSimpleName = data.shopSimpleName;
  streamShopForm.companyName = data.companyName;
  streamShopForm.marketer = data.marketer;
  streamShopForm.status = data.status;
  streamShopForm.createTime = data.createTime;
};
const clearForm = () => {
  // 重置表单字段
  streamShopForm.id = '';
  streamShopForm.shopCode = '';
  streamShopForm.shopPlatform = '';
  streamShopForm.shopFullName = '';
  streamShopForm.shopSimpleName = '';
  streamShopForm.companyName = '';
  streamShopForm.marketer = '';
  streamShopForm.status = 0; // 假设默认状态是0
  streamShopForm.createTime = '';
};

//编辑
const handleUpdateStreamShop = () => {
     if (streamShopRef.value === null) {
       console.error("streamShopRef is null");
       return;
     }
     streamShopRef.value.validate().then(() => {
       ElMessageBox.confirm("确认提交?").then(() => {
         editStreamShop(streamShopForm).then((res) => {
           if (res.code === 200) {
             ElMessage.success("修改成功");
           } else {
             ElMessage.error(res.msg);
           }
           dialogVisible2.value = false;
           handleGetStreamShopList(state.data.page, state.data.limit);
           clearForm();
         });
       });
     });
   };
    const handleClose = (e) => { //提交表单
      ElMessageBox.confirm('确认提交?')
        .then(() => {
          done()
        })
        .catch(() => {
          // catch error
        })
    }

 //切换店铺状态

const handleSelectionChange = (val) => {
  selectedRows.value = val;
};
//启用
const handleChangeStatus = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个店铺进行操作');
    return;
  }

  for (const selectedRow of selectedRows.value) {
    const statusValue = Number(selectedRow.status);
    if (statusValue === 0) {
      ElMessage.info('当前状态为启用状态，无需改变');
    } else {
      try {
        const wmsStreamShopList = [{
          id: Number(selectedRow.id),
          status: '0' // 确保这是后端期望的数据类型
        }];

        const result = await startOrStopStreamShop(wmsStreamShopList);
        if (result.code === 200) {
          selectedRow.status = 0;
          ElMessage.success('状态更新成功');
        } else {
          ElMessage.error(result.msg || '状态更新失败');
        }
      } catch (error) {
        console.error('状态更新请求失败:', error);
        ElMessage.error('状态更新请求失败');
      }
    }
  }

  handleGetStreamShopList(state.data.page, state.data.limit);
};

const handleChangeStatus1 = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个店铺进行操作');
    return;
  }

  for (const selectedRow of selectedRows.value) {
    const statusValue = Number(selectedRow.status);
    if (statusValue === 1) {
      ElMessage.info('当前状态为停用状态，无需改变');
    } else {
      try {
        const wmsStreamShopList = [{
          id: Number(selectedRow.id),
          status: '1' // 确保这是后端期望的数据类型
        }];

        const result = await startOrStopStreamShop(wmsStreamShopList);
        if (result.code === 200) {
          selectedRow.status = 1;
          ElMessage.success('状态更新成功');
        } else {
          ElMessage.error(result.msg || '状态更新失败');
        }
      } catch (error) {
        console.error('状态更新请求失败:', error);
        ElMessage.error('状态更新请求失败');
      }
    }
  }

  handleGetStreamShopList(state.data.page, state.data.limit);
};


    return {
      streamShopData,
      dialogVisible1,
      dialogVisible2,
      searchForm,
      streamShopForm,
      streamShopRules,
      tableData, filterTag,startOrStopStreamShop,editStreamShop,
      handleCurrentChange,handleSelectionChange,handleChangeStatus,handleChangeStatus1,
      handleSizeChange,addStreamShop,
      handleClose,streamShopRef ,handleUpdateStreamShop,
      handleDeleteStreamShop, handleAddStreamShop, handleGetStreamShopList,
      handleOpenEdit,
      ...toRefs(state),
    };
  },
});
</script>
    
<style rel="stylesheet/scss" lang="scss" scoped>
.front {
  background-color: #fff;
  padding: 10px;
  display: flex;

  .input {
    float: left;
  }

  .search {
    margin-left: 50px;
  }
}

.center {
  margin: 10px;
}

.form-add-checkbox {
  width: 200px;
  height: 260px;
  display: block;
  border: solid 1px #c9c9c9;

  .form-add-checkbox-item {
    width: 180px;
    margin: auto;
  }
}

.tail {
  background-color: #fff;
  margin-top: 40px;
  padding: 10px;

  .tail-action {
    margin-bottom: 10px;
    display: flex;
  }
}
</style>